package com.quick.framework.manager;


import com.quick.common.utils.ThreadUtils;
import com.quick.common.utils.spring.SpringUtils;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.TimerTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 异步任务管理器
 *
 * @Author: Administrator
 * @Date: 2023/7/27
 */
public class AsyncManager {
    /**
     * 延迟10毫秒
     */
    private final static int OPERATE_DELAY_TIME = 10;

    /**
     * 异步操作任务调度线程池
     */
    private final ScheduledExecutorService executor = SpringUtils.getBean(ScheduledExecutorService.class);

    /**
     * 单例模式
     */
    private AsyncManager() {

    }

    private static final AsyncManager ME = new AsyncManager();

    public static AsyncManager getInstance() {
        return ME;
    }

    /**
     * 执行任务
     *
     * @param task 任务
     */
    public void execute(TimerTask task) {
        executor.schedule(task, OPERATE_DELAY_TIME, TimeUnit.MILLISECONDS);
    }

    /**
     * 停止任务线程池
     */
    public void shutdown() {
        ThreadUtils.shutdownAndAwaitTermination(executor);
    }
}
